from rest_framework.views import APIView
from .serializers import *
from .utils import RespBean
from django.contrib.auth.hashers import make_password, check_password
import logging
logger = logging.getLogger(__name__)


# 登录与注册
class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        if not username or not password:
            return RespBean.error("用户名和密码不能为空")

        try:
            user = LoginUser.objects.get(username=username)
            if password == user.password:
                return RespBean.success("登录成功", {
                    'user_id': user.id,
                    'username': user.username
                })
            return RespBean.error("用户名或密码错误")
        except LoginUser.DoesNotExist:
            logger.error(f"User not found: {username}")
            return RespBean.error("用户不存在")
        except Exception as e:
            logger.error(f"Login error for user {username}: {str(e)}", exc_info=True)
            return RespBean.error("登录失败，请稍后重试")


class RegisterView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        if not username or not password:
            return RespBean.error("用户名或密码不能为空")

        hashed_password = make_password(password)
        LoginUser.objects.create(username=username, password=hashed_password)
        return RespBean.success("注册成功")


class UserListView(APIView):
    def get(self, request):
        try:
            users = LoginUser.objects.all()
            serializer = LoginUserSerializer(users, many=True)
            return RespBean.success("获取用户列表成功", serializer.data)
        except Exception as e:
            logger.error("Failed to fetch user list", exc_info=True)
            return RespBean.error("获取用户列表失败")


class LoginUserSearch(APIView):
    def get(self, request):
        try:
            username = request.query_params.get('username')
            password = request.query_params.get('password')

            users = LoginUser.objects.all()
            if username:
                users = users.filter(username__icontains=username)
            if password:
                users = users.filter(password=password)

            serializer = LoginUserSerializer(users, many=True)
            return RespBean.success("搜索用户成功", serializer.data)
        except Exception as e:
            logger.error(f"Failed to search users with username: {username} and password: {password}", exc_info=True)
            return RespBean.error("搜索用户失败")

# 文章部分
class ArticleList(APIView):
    def get(self, request):
        try:
            articles = Article.objects.all()
            serializer = ArticleSerializer(articles, many=True)
            return RespBean.success("查询成功", serializer.data)
        except Exception as e:
            logger.error("Failed to fetch article list", exc_info=True)
            return RespBean.error("获取数据失败")

    def post(self, request):
        try:
            serializer = ArticleSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return RespBean.success("数据添加成功")
            return RespBean.error("数据不能为空")
        except Exception as e:
            logger.error("Failed to add article", exc_info=True)
            return RespBean.error("添加数据失败")


class ArticleSearch(APIView):
    def get(self, request):
        try:
            code = request.query_params.get('code')
            name = request.query_params.get('name')
            status = request.query_params.get('status')

            articles = Article.objects.all()
            if code:
                articles = articles.filter(code=code)
            if name:
                articles = articles.filter(name__icontains=name)
            if status:
                articles = articles.filter(status=status)

            serializer = ArticleSerializer(articles, many=True)
            return RespBean.success("查询成功", serializer.data)
        except Exception as e:
            logger.error(f"Failed to search articles with code: {code}, name: {name}, status: {status}", exc_info=True)
            return RespBean.error("查询失败")


class ArticleDetail(APIView):
    def delete(self, request, id):
        try:
            article = Article.objects.get(id=id)
            article.delete()
            return RespBean.success("删除成功")
        except Exception as e:
            logger.error(f"Failed to delete article with id: {id}", exc_info=True)
            return RespBean.error("删除失败")

    def post(self, request, id):
        try:
            article = Article.objects.get(id=id)
            serializer = ArticleSerializer(article, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return RespBean.success("更新成功")
            return RespBean.error("数据不能为空")
        except Exception as e:
            logger.error(f"Failed to update article with id: {id}", exc_info=True)
            return RespBean.error("更新失败")


# 订单
class OrderView(APIView):
    def get(self, request):
        try:
            orders = Order.objects.all()
            serializer = OrderSerializer(orders, many=True)
            return RespBean.success("查询成功", serializer.data)
        except Exception as e:
            logger.error("Failed to fetch order list", exc_info=True)
            return RespBean.error("获取数据失败")

    def post(self, request):
        try:
            serializer = OrderSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return RespBean.success("数据添加成功")
            return RespBean.error("字段不能为空")
        except Exception as e:
            logger.error("Failed to add order", exc_info=True)
            return RespBean.error("添加数据失败")


class OrderSearch(APIView):
    def get(self, request):
        try:
            name = request.query_params.get('name')
            code = request.query_params.get('code')

            orders = Order.objects.all()
            if name:
                orders = orders.filter(name__icontains=name)
            if code:
                orders = orders.filter(code=code)

            serializer = OrderSerializer(orders, many=True)
            return RespBean.success("查询成功", serializer.data)
        except Exception as e:
            logger.error(f"Failed to search orders with name: {name} and code: {code}", exc_info=True)
            return RespBean.error("查询失败")


class OrderDetailView(APIView):
    def delete(self, request, id):
        try:
            order = Order.objects.get(id=id)
            order.delete()
            return RespBean.success("数据删除成功")
        except Exception as e:
            logger.error(f"Failed to delete order with id: {id}", exc_info=True)
            return RespBean.error("数据删除失败")

    def post(self, request):
        try:
            id = request.data.get('id')
            if not id:
                return RespBean.error('id不能为空')

            # 查询订单
            order = Order.objects.get(id=id)
            serializer = OrderSerializer(order, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return RespBean.success("订单更新成功")
            return RespBean.error("字段验证失败", data=serializer.errors)

        except Order.DoesNotExist:
            logger.error(f"Failed to update order with id: {id}", exc_info=True)
            return RespBean.not_found("未找到订单")
        except Exception as e:
            logger.error(f"Failed to update order with id: {id}", exc_info=True)
            return RespBean.error("数据更新失败")

# 课程用户
class UserView(APIView):
    def get(self, request):
        try:
            users = User.objects.all()
            serializer = UserSerializer(users, many=True)
            return RespBean.success("数据获取成功", serializer.data)
        except Exception as e:
            logger.error("Failed to fetch user list", exc_info=True)
            return RespBean.error("获取用户列表失败")

    def post(self, request):
        try:
            user_data = request.data
            if not all(key in user_data for key in
                       ['id', 'name', 'sex', 'nickname', 'mobile', 'stateName', 'courseOrder', 'courseNum', 'address']):
                return RespBean.error("字段不能为空")

            serializer = UserSerializer(data=user_data)
            if serializer.is_valid():
                serializer.save()
                return RespBean.success("用户添加成功")
            return RespBean.error("用户添加失败: " + str(serializer.errors))
        except Exception as e:
            logger.error("Failed to add user", exc_info=True)
            return RespBean.error("用户添加失败: " + str(e))


class UserSearch(APIView):
    def get(self, request):
        try:
            name = request.query_params.get('name')
            sex = request.query_params.get('sex')

            users = User.objects.all()
            if name:
                users = users.filter(name__icontains=name)
            if sex:
                users = users.filter(sex=sex)

            serializer = UserSerializer(users, many=True)
            return RespBean.success("查询成功", serializer.data)
        except Exception as e:
            logger.error(f"Failed to search users with name: {name} and sex: {sex}", exc_info=True)
            return RespBean.error("查询失败: " + str(e))


class UserDetailView(APIView):
    def delete(self, request, id):
        try:
            user = User.objects.get(id=id)
            user.delete()
            return RespBean.success("用户删除成功")
        except User.DoesNotExist:
            logger.error(f"Failed to delete user with id: {id}", exc_info=True)
            return RespBean.error("用户不存在")
        except Exception as e:
            logger.error(f"Failed to delete user with id: {id}", exc_info=True)
            return RespBean.error("用户删除失败: " + str(e))

    def post(self, request, id):
        try:
            user = User.objects.get(id=id)
            serializer = UserSerializer(user, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return RespBean.success("用户更新成功")
            return RespBean.error("字段不能为空")
        except User.DoesNotExist:
            return RespBean.not_found("未找到用户")


# 自定义视图
class ZybTrackerStatisticsAction(APIView):
    def get(self, request):
        # 处理请求逻辑
        data = request.GET.get('data', {})
        callback = request.GET.get('__callback__', '')
        response_data = {
            'status': 'success',
            'data': data,
        }
        return RespBean.success(callback, response_data)
